package com.yusvn.scm.goods.buhuo.service;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.yitter.idgen.YitIdHelper;
import com.jfinal.aop.Inject;
import com.jfinal.kit.Kv;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.yusvn.scm.admin.service.LoginService;
import com.yusvn.scm.common.BaseService;
import com.yusvn.scm.common.constant.Const;
import com.yusvn.scm.common.kit.RetKit;

import java.util.ArrayList;
import java.util.List;


public class ScmBuhuoZbbhService extends BaseService {

	@Inject
	LoginService loginService;

	@Inject
	ScmBuhuoMdbhService mdbhService;

    /**
     * 总部补货查询
     */
    public List<Record> selectALlBh(Kv kv) {
        kv.set("cid", getCid());
        kv.set(selectPz()); //商品属性动态字段
        kv.set("goodsimg", getGoodsimg());
		kv.set("qx_pp", getPpqx(kv.getStr("userCode"))); //用户品牌权限
        List<Record> records = Db.use(Const.SCMDB).template("scmBuhuoZbbh.getZbbhsp", kv).find();
        return records;
    }

    /**
     * 总部查询本次补货明细
     */
    public List<Record> selectBcbhmx(Kv kv) {
        kv.set("cid", getCid());
        kv.set(selectPz()); //商品属性动态字段
		kv.set("qx_pp", getPpqx(kv.getStr("userCode"))); //用户品牌权限
        return Db.use(Const.SCMDB).template("scmBuhuoZbbh.getZbbhmx", kv).find();
    }

    /**
     * 门店提交情况
     */
    public List<Record> mdCommit(Kv kv) {
        kv.set("cid", getCid());
        kv.set(selectPz()); //商品属性动态字段
		kv.set("qx_pp", getPpqx(kv.getStr("userCode"))); //用户品牌权限
    	return Db.use(Const.SCMDB).template("scmBuhuoZbbh.mdCommit", kv).find();
    }

    /**
     * 获取所有店某个商品的颜色尺码，用于新增
     */
    public List<Record> getSpyscm(Kv kv) {
        kv.set("cid", getCid());

        return Db.use(Const.SCMDB).template("scmBuhuoZbbh.getSpyscm", kv).find();
    }

    /**
     * 获取某个商品补货数据， 用于修改补货数量
     */
    public List<Record> selectBhmx(Kv kv) {
        kv.set("cid", getCid());

        return Db.use(Const.SCMDB).template("scmBuhuoZbbh.getBhmd", kv).find();
    }

    /**
     * 开启审核
     */
    public RetKit toExamine(Kv kv) {
    	kv.set("cid", getCid());
        kv.set(selectPz()); //商品属性动态字段

    	//判断是否到了补货时间
    	RetKit retBhsj = mdbhService.buHuoShiJian(kv);
    	if(retBhsj.isFail()) {
    		return retBhsj;
    	}

        //前端勾选的门店区域提交情况
        String checkList = kv.getStr("checkList");
        if(null==checkList || checkList.equals("[]")) {
        	return RetKit.fail("请选择要审核的数据");
        }
        JSONArray idsArr = JSONArray.parseArray(checkList);
		Object[][] paras = new Object[idsArr.size()][2];
		for(int i=0;i<idsArr.size();i++) {
			JSONObject obj = idsArr.getJSONObject(i); JSONObject.parseObject(idsArr.get(i).toString());
			paras[i][0] = obj.get("mdid");
			paras[i][1] = obj.get("ppid");
		}

		int[] cntArr = Db.use(Const.SCMDB).batch("update scm_buhuo_mdbhjg set sfsh=1, shrq=SYSDATE where mdid=? and ppid=? ", paras, 100);

		//统计成功行数
		int cntOk = 0;
		for(int i=0; i<cntArr.length; i++) {
			if(cntArr[i]==-2 || cntArr[i]==1) { //oracle返回-2、sqlserver返回1，表示成功
				cntOk++;
			}
		}
		if(cntArr.length>0) {
			return RetKit.ok("成功开启审核了 "+cntOk);
		}
		return RetKit.fail("开启审核失败");
    }

    /**
     * 关闭审核
     */
    public RetKit toExamineQx(Kv kv) {
    	kv.set("cid", getCid());
        kv.set(selectPz()); //商品属性动态字段

    	//判断是否到了补货时间
    	RetKit retBhsj = mdbhService.buHuoShiJian(kv);
    	if(retBhsj.isFail()) {
    		return retBhsj;
    	}

        //前端勾选的门店区域提交情况
        String checkList = kv.getStr("checkList");
        if(null==checkList || checkList.equals("[]")) {
        	return RetKit.fail("请选择要审核的数据");
        }
        JSONArray idsArr = JSONArray.parseArray(checkList);
		Object[][] paras = new Object[idsArr.size()][2];
		for(int i=0;i<idsArr.size();i++) {
			JSONObject obj = idsArr.getJSONObject(i); JSONObject.parseObject(idsArr.get(i).toString());
			paras[i][0] = obj.get("mdid");
			paras[i][1] = obj.get("ppid");
		}

		int[] cntArr = Db.use(Const.SCMDB).batch("update scm_buhuo_mdbhjg set sfsh=0, shrq=SYSDATE where mdid=? and ppid=? ", paras, 100);

		//统计成功行数
		int cntOk = 0;
		for(int i=0; i<cntArr.length; i++) {
			if(cntArr[i]==-2 || cntArr[i]==1) { //oracle返回-2、sqlserver返回1，表示成功
				cntOk++;
			}
		}
		if(cntArr.length>0) {
			return RetKit.ok("成功关闭审核了 "+cntOk);
		}
		return RetKit.fail("关闭审核失败");
    }

    /**
     * 生成单据
     * 1每个店每个区域生成一张采购单。
     * 2总部采购人员只生成自己区域的采购单。
     * 3门店确认并提交的款且总部确认的款才能生成单据。(排除已删除的款)
     */
    public RetKit scdj(Kv kv) {
        kv.set(selectPz()); //商品属性动态字段

		//账套id
		String cid = getCid();
		kv.set("cid", cid);
		String userid=kv.getStr("userid"); //当前智能商品系统的登录用户id

		//获取原erp用户id
		String erpUserid = loginService.getErpUserId(kv.get("userid"), cid);
		kv.set("erpUserid", erpUserid);

    	//判断是否到了补货时间
    	RetKit retBhsj = mdbhService.buHuoShiJian(kv);
    	if(retBhsj.isFail()) {
    		return retBhsj;
    	}

    	//用户品牌权限
    	List<String> qx_pp = getPpqx(kv.getStr("userCode"));
		kv.set("qx_pp", qx_pp);

    	//判断总部是否开启审核了
        RetKit sfsh = shenHe(kv);
        if(sfsh.isFail()) {
        	return sfsh;
        }

        //前端勾选的要生成单据的数据
        String checkList = kv.getStr("checkList");
        if(null==checkList || checkList.equals("[]")) {
        	return RetKit.fail("请选择要生成单据的数据");
        }
		try {
			//存入用户勾选的id到临时表 (因存储过程不能传递数组参数，这个是方便存储过程中操作)
			JSONArray idsArr = JSON.parseArray(checkList);
			Object[][] paras = new Object[idsArr.size()][3];
			List<String> parasList = new ArrayList<String>();
			for(int i=0;i<idsArr.size();i++) {
				JSONObject obj = idsArr.getJSONObject(i); JSONObject.parseObject(idsArr.get(i).toString());
				paras[i][0] = obj.get("mdid")+"_"+obj.get("ppid"); //门店ID_品牌ID拼接成ids   //idsArr.get(i);
				paras[i][1] = cid;
				paras[i][2] = userid;

				parasList.add(obj.get("mdid")+"_"+obj.get("ppid"));
			}

			//判断能生成单据的补货数量是否大于0
			kv.set("mdppId", parasList); //门店品牌ID的拼接参数
			Long scdjSl = Db.use(Const.SCMDB).template("scmBuhuoZbbh.getScdjSl", kv).queryLong();
			if(null==scdjSl || scdjSl<=0) {
				return RetKit.fail("没有补货数据能生成单据");
			}

			//先删除之前临时表用户勾选的id
			Db.use(Const.SCMDB).update("delete from scm_base_ids where cid=? and userid=? and lx='zbbh_scdj' ", cid, userid);
			//Thread.sleep(1000*5); // 休眠5秒
			Db.use(Const.SCMDB).batch("insert into scm_base_ids(id, cid, lx, userid) values(?, ?, 'zbbh_scdj', ?)", paras, 500);

			//调用存储过程生成采购订单存储（传参：ERP的账套id\智能商品系统的用户id\ERP系统的用户ID\今天日期）
			Db.use(Const.SCMDB).update("CALL proc_scm_sccgdd(?,?,?,?) ", getCid(), userid, erpUserid, DateUtil.date() );  //, kv.getDate("djDate1")

			//删除临时表用户勾选的id
			Db.use(Const.SCMDB).update("delete from scm_base_ids where cid=? and userid=? and lx='zbbh_scdj' ", cid, userid);

		} catch (Exception e) {
			e.printStackTrace();
			return RetKit.fail("生成单据失败:"+e.getMessage() );
		}
		return RetKit.ok("生成单据成功");
    }

    /**
     * 修改总部补货数量
     */
    public RetKit updateZbbhsl(Kv kv) {
    	kv.set("cid", getCid());
    	String mdid = kv.getStr("mdid"); //门店ID

    	//判断总部是否开启审核了
        RetKit sfsh = shenHe(kv);
        if(sfsh.isFail()) {
        	return sfsh;
        }

        //判断需补货数据在补货结果明细表中是否存在
        Integer cnt = Db.use(Const.SCMDB).queryInt("select count(1) as cnt from scm_buhuo_mdbhjgmx where mdid=? and spid=? and ysid=? and cmid=? "
        		, mdid, kv.get("spid"), kv.get("ysid"), kv.get("cmid"));

        if(null==cnt || 0 >= cnt) { // || cnt<=0
        	//获取商品信息
        	Record rec = Db.use(Const.SCMDB).findFirst("select sku.id as skuid, sp.ATTRIB1 as ppid  " +
        			"from defsku sku " +
        			"left join DEFSTYLE sp on sku.STYLEID=sp.ID " +
        			"where sku.cid=? and sku.STYLEID=? and sku.clrid=? and sku.sizeid=?"
        			, kv.get("cid"), kv.get("spid"), kv.get("ysid"),kv.get("cmid") );
        	//新增  （总部新增或修改了，要更新这个款改成门店已确认mdqr=1）
        	Db.use(Const.SCMDB).update("insert into scm_buhuo_mdbhjgmx(id, mdid, spid, ysid, cmid,  skuid, ppid, jybhsl, sjbhsl, sjzt,  mdqr) "
        			+ "values(?,?,?,?,?, ?,?,?,?,?, ?) "
        			,YitIdHelper.nextId(), mdid, kv.get("spid"), kv.get("ysid"), kv.get("cmid")
        			, rec.get("skuid"), rec.get("ppid"), 0, kv.get("sjbhsl"), 6 ,1);

            return RetKit.ok("新增成功");
        }else {
            Integer qty = Db.use(Const.SCMDB).queryInt("select max(nvl(sjbhsl,0)) as sjbhsl from scm_buhuo_mdbhjgmx where mdid=? and spid=? and ysid=? and cmid=? "
            		, mdid, kv.get("spid"), kv.get("ysid"), kv.get("cmid"));
        	if(qty.equals(kv.getInt("sjbhsl"))) { //如果修改数量等于原实际补货数量，则不用修改
        		return RetKit.fail("未修改数量");
        	}

        	//修改  （总部新增或修改了，要更新这个款改成门店已确认mdqr=1）
        	Db.use(Const.SCMDB).update("update scm_buhuo_mdbhjgmx set sjbhsl=?, sjzt=5, mdqr=1 where mdid=? and spid=? and ysid=? and cmid=? "
        			, kv.get("sjbhsl"), mdid, kv.get("spid"), kv.get("ysid"), kv.get("cmid"));

        	return RetKit.ok("修改成功");
        }
    }

    /**
     * 总部新增门店
     */
    public RetKit insertStore(Kv kv) {
        kv.set("cid", getCid());
    	String mdid = kv.getStr("mdid"); //门店ID

    	//判断总部是否开启审核了
        RetKit sfsh = shenHe(kv);
        if(sfsh.isFail()) {
        	return sfsh;
        }

        //判断补货结果明细表中是否有需要新增门店的这个款色
        int cnt = Db.use(Const.SCMDB).queryInt("select count(*) from scm_buhuo_mdbhjgmx where mdid=? and spid=? and ysid=? "
        		, mdid, kv.get("spid"), kv.get("ysid") );

        if(cnt<=0) {
        	//获取商品其中一个尺码
        	Record rec = Db.use(Const.SCMDB).findFirst("select sku.id as skuid, sp.ATTRIB1 as ppid, sku.sizeid as cmid " +
        			"from defsku sku " +
        			"left join DEFSTYLE sp on sku.STYLEID=sp.ID " +
        			"where sku.cid=? and sku.STYLEID=? and sku.clrid=? "
        			, kv.get("cid"), kv.get("spid"), kv.get("ysid") );
        	//新增一行空数据  （总部新增或修改了，要更新这个款改成门店已确认mdqr=1）
        	Db.use(Const.SCMDB).update("insert into scm_buhuo_mdbhjgmx(id, mdid, spid, ysid, cmid,  skuid, ppid, jybhsl, sjbhsl, bz,  sjzt, mdqr) "
        			+ "values(?,?,?,?,?, ?,?,?,?,?, ?,?) "
        			,YitIdHelper.nextId(), mdid, kv.get("spid"), kv.get("ysid"), rec.get("cmid") //注意尺码ID是sql查询出的
        			, rec.get("skuid"), rec.get("ppid"), 0, 0, kv.get("bz"), 6, 1);

            return RetKit.ok("新增成功，请录入此门店补货数量");
        }else {
        	return RetKit.fail("此门店已存在补货数据");
        }
    }

    /**
     * 总部新增某个商品的补货
     */
    public RetKit insertZbbh(Kv kv) {
        kv.set("cid", getCid());
    	String mdid = kv.getStr("mdid"); //门店ID

    	//判断总部是否开启审核了
        RetKit sfsh = shenHe(kv);
        if(sfsh.isFail()) {
        	return sfsh;
        }

        //判断需补货数据在补货结果明细表中是否存在
        int cnt = Db.use(Const.SCMDB).queryInt("select count(*) from scm_buhuo_mdbhjgmx where mdid=? and spid=? and ysid=? and cmid=? "
        		, mdid, kv.get("spid"), kv.get("ysid"), kv.get("cmid"));

        if(cnt<=0) {
        	//获取商品信息
        	Record rec = Db.use(Const.SCMDB).findFirst("select sku.id as skuid, sp.ATTRIB1 as ppid  " +
        			"from defsku sku " +
        			"left join DEFSTYLE sp on sku.STYLEID=sp.ID " +
        			"where sku.cid=? and sku.STYLEID=? and sku.clrid=? "
        			, kv.get("cid"), kv.get("spid"), kv.get("ysid") );
        	//新增  （总部新增或修改了，要更新这个款改成门店已确认mdqr=1）
        	Db.use(Const.SCMDB).update("insert into scm_buhuo_mdbhjgmx(id, mdid, spid, ysid, cmid,  skuid, ppid, jybhsl, sjbhsl, sjzt,  mdqr) "
        			+ "values(?,?,?,?,?, ?,?,?,?,?, ?) "
        			,YitIdHelper.nextId(), mdid, kv.get("spid"), kv.get("ysid"), kv.get("cmid")
        			, rec.get("skuid"), rec.get("ppid"), 0, kv.get("sjbhsl"), 6,  1);

            return RetKit.ok("新增成功");
        }else {
        	return RetKit.fail("此商品条码已存在补货数据");
        }
    }

    /**
     * 批量删除不需要补货的商品
     * @param delList
     * @return
     */
    public RetKit deletePlsp(String delList) {
    	Kv kv = Kv.create();
        kv.set("cid", getCid());
        kv.set(selectPz()); //商品属性动态字段

    	//判断总部是否开启审核了
        RetKit sfsh = shenHe(kv);
        if(sfsh.isFail()) {
        	return sfsh;
        }

        JSONObject jsonObject = JSON.parseObject(delList);
        JSONArray idsArr = JSONArray.parseArray(jsonObject.getString("delList"));
		Object[][] paras = new Object[idsArr.size()][2];
		for(int i=0;i<idsArr.size();i++) {
			JSONObject obj = idsArr.getJSONObject(i); JSONObject.parseObject(idsArr.get(i).toString());
			paras[i][0] = obj.get("spid");
			paras[i][1] = obj.get("ysid");
		}

		int[] cntArr = Db.use(Const.SCMDB).batch("update scm_buhuo_mdbhjgmx set zbsc=1, zbqr=0, sjzt=5 where spid=? and ysid=? ", paras, 100);

		//统计成功行数
		int cntOk = 0;
		for(int i=0; i<cntArr.length; i++) {
			if(cntArr[i]==-2 || cntArr[i]==1) { //oracle返回-2、sqlserver返回1，表示成功
				cntOk++;
			}
		}
		if(cntArr.length>0) {
			return RetKit.ok("成功删除 "+cntOk+" 条数据");
		}

		return RetKit.fail("批量删除失败");
    }

    /**
     * 总部确认某商品补货
     * @param kv
     * @return
     */
    public RetKit zbbhQrsp(Kv kv) throws Exception {
    	kv.set("cid", getCid());

    	//判断总部是否开启审核了
        RetKit sfsh = shenHe(kv);
        if(sfsh.isFail()) {
        	return sfsh;
        }

        //更新门店某款色的确认状态
        Db.use(Const.SCMDB).templateByString("update scm_buhuo_mdbhjgmx set zbqr=#(zbqr) "
        		+ "where spid=#(spid) and ysid=#(ysid) "
        		+ "", kv).update();

		return RetKit.ok("确认成功");
    }

    /**
     * 判断是否审核状态
     */
    public RetKit shenHe(Kv kv) {
        //kv.set("cid", getCid());

    	//判断是否到了补货时间
    	RetKit retBhsj = mdbhService.buHuoShiJian(kv);
    	if(retBhsj.isFail()) {
    		return retBhsj;
    	}

        //判断是否审核
        int sfsh = Db.use(Const.SCMDB).templateByString("select count(*) as cnt from scm_buhuo_mdbhjg a "
                		+ "where 1=1 "
                		+ " and a.sfsh=1 " //a.sfsh=1 表示总部审核中
                		+ "", kv).queryInt();
        if(sfsh>0) {
        	return RetKit.ok("数据在审核中").set("sfsh", "1");
        }

        return RetKit.fail("未开启审核").set("sfsh", "0");
    }

    /**
     * 获取门店补货进度、补货时间、补货数量
     * @param kv
     * @return
     */
    public Record getBhsj(Kv kv) {
    	kv.set("cid", getCid());
        kv.set(selectPz()); //商品属性动态字段
		kv.set("qx_pp", getPpqx(kv.getStr("userCode"))); //用户品牌权限

        //补货进度bhjd、补货日期bhrq、
        Record rec = Db.use(Const.SCMDB).templateByString("select case when max(a.sfsh)=1 then '审核中' when max(a.sftj)=1 then '已提交' else '未提交' end as bhjd "
        		+ ", min(a.bhrq) as bhrq "
        		+ "from scm_buhuo_mdbhjg a "
        		+ "where 1=1 "
				+ "#if(qx_pp) " //用户品牌权限
				+ "        and ("
				+ "            #for(x : qx_pp)"
				+ "                a.ppid = '#(x)'"
				+ "                #(for.last ? '' : 'or')"
				+ "            #end "
				+ "        )"
				+ "    #end", kv).findFirst();

		//实际补货数量、建议补货数量
        Record rec2 = Db.use(Const.SCMDB).templateByString("select sum(a.sjbhsl) as sjbhsl, sum(a.jybhsl) as jybhsl "
        		+ "from scm_buhuo_mdbhjgmx a "
        		+ "left join scm_buhuo_mdbhjg b on a.mdid=b.mdid and a.ppid=b.ppid "
        		+ "where 1=1 and a.mdsc=0 and a.zbsc=0 " // -- 排除被门店和总部删除的款
        		+ "and b.sftj=1 " //  -- 门店已提交
        		+ "and a.mdqr=1 " //  -- 门店已确认
				+ "#if(qx_pp) " //用户品牌权限
				+ "        and ("
				+ "            #for(x : qx_pp)"
				+ "                a.ppid = '#(x)'"
				+ "                #(for.last ? '' : 'or')"
				+ "            #end "
				+ "        )"
				+ "    #end", kv).findFirst();

        rec.set("sjbhsl", rec2.get("sjbhsl"));
        rec.set("jybhsl", rec2.get("jybhsl"));

        return rec;
    }

	/**
	 * 总部表2 总部代替确认某门店可以补货
	 * @param kv
	 * @return
	 */
    public RetKit updateSftjqr(Kv kv){
		int update = Db.use(Const.SCMDB).template("scmBuhuoZbbh.updateZbtjqr",kv).update();

		Record first = Db.use(Const.SCMDB).templateByString("select ppid from scm_buhuo_mdbhjgmx where mdid = #(mdid) and spid = #(spid) and ysid = #(ysid)",
				kv).findFirst();

		Db.use(Const.SCMDB).update("update scm_buhuo_mdbhjg set sftj = 1 where mdid = ? and ppid = ?"
		,kv.get("mdid"), first.get("ppid"));
		if (update > 0){
			return RetKit.ok("确认成功");
		}
		return RetKit.fail("确认失败");
	}
	/**
	 * 总部打印查询
	 */
	public List<Record> zbdycx(Kv kv){
			//用户品牌权限
			List<String> qx_pp = getPpqx(kv.getStr("userCode"));
			kv.set("qx_pp", qx_pp);

			JSONArray idsArr = JSON.parseArray(kv.get("dyList").toString());
			List<String> parasList = new ArrayList<String>();
			for(int i=0;i<idsArr.size();i++) {
				JSONObject obj = idsArr.getJSONObject(i); JSONObject.parseObject(idsArr.get(i).toString());
				parasList.add(obj.get("mdid")+"_"+obj.get("ppid"));  //门店ID_品牌ID拼接成ids   //idsArr.get(i);
			}
			//判断能生成单据的补货数量是否大于0
			kv.set("mdppId", parasList); //门店品牌ID的拼接参数
			List<Record> records = Db.use(Const.SCMDB).template("scmBuhuoZbbh.zbdycx",kv).find();

		return records;
	}

	/**
	 * 修改打印次数
	 */
	public RetKit xgdycs(Kv kv){
		JSONArray idsArr = JSON.parseArray(kv.get("dyList").toString());
		Object[][] paras = new Object[idsArr.size()][2];
		for(int i=0;i<idsArr.size();i++) {
			JSONObject obj = idsArr.getJSONObject(i); JSONObject.parseObject(idsArr.get(i).toString());
			paras[i][0] = obj.get("mdid");
			paras[i][1] = obj.get("ppid");
		}
		int[] cntArr = Db.use(Const.SCMDB).batch("update scm_buhuo_mdbhjg a  set "
						+ "a.dycs = nvl(dycs,0)+1 where a.mdid = ? and a.ppid = ?"
						+ "and EXISTS ("
						+ "SELECT 1 "
						+ "FROM scm_buhuo_mdbhjgmx b "
						+ "WHERE a.mdid = b.mdid AND a.ppid = b.ppid AND b.mdqr = 1)"
				, paras, 100);
		if(cntArr.length>0) {
			return RetKit.ok("更新打印次数成功");
		}
		return RetKit.fail("更新打印次数失败");

	}

	public List<Record> cxZbkscgsl(Kv kv){
		kv.set("cid",getCid());
		List<Record> records = Db.use(Const.SCMDB).template("scmBuhuoZbbh.cxZbkscgsl",kv).find();
		return records;
	}

	/**
	 * 获取商品图片和供应商
	 */
	public Record getPstpGys(Kv kv){
		kv.set("cid", getCid()); //账套id
		//获取商品图片地址
		kv.set("goodsimg", getGoodsimg());
		return Db.use(Const.SCMDB).template("scmBuhuoZbbh.getPstpGys", kv).findFirst();
	}

	/**
	 * 总部打印选择列
	 * @param kv
	 * @return
	 */
	public List<Record> dycxAll(Kv kv){
		kv.set("cid", getCid()); //账套id
		kv.set("qx_pp", getPpqx(kv.getStr("userCode"))); //用户品牌权限
		String cgddbhlx = Db.use(Const.SCMDB).queryStr("select pz1 from scm_pzbh where bh = 'scm_buhuo_cgddbhlx'");
		kv.set("cgddbhlx",cgddbhlx);
		List<Record> records = Db.use(Const.SCMDB).template("scmBuhuoZbbh.dycxAll",kv).find();
		return records;
	}

	public List<Record> zbcxDysj(Kv kv){
		JSONArray idsArr = JSON.parseArray(kv.get("checkList").toString());
		List<String> parasList = new ArrayList<>();
		for(int i=0;i<idsArr.size();i++) {
			JSONObject obj = idsArr.getJSONObject(i); 
			//JSONObject.parseObject(idsArr.get(i).toString());
			parasList.add(obj.get("djbh").toString());
		}
		kv.set("cid", getCid());
		kv.set("cx_cans",parasList);
		String cgddbhlx = Db.use(Const.SCMDB).queryStr("select pz1 from scm_pzbh where bh = 'scm_buhuo_cgddbhlx'");
		kv.set("cgddbhlx",cgddbhlx);
		//启用门店简称
		String mdjc = Db.use(Const.SCMDB).queryStr("select pz2 from scm_pzbh where bh = 'scm_buhuo_mdjc'");
		kv.set("mdjc",mdjc);
		List<Record> records = Db.use(Const.SCMDB).template("scmBuhuoZbbh.zbcxDysj",kv).find();
		return records;
	}

	/**
	 * 查询补货打印抬头
	 */
	public Record dytt(Kv kv){

		Record first = Db.use(Const.SCMDB).findFirst("select pz1 from scm_pzbh where bh = 'scm_buhuo_dytt'");
		return first;
	}


	/**
	 * 同步补货明细到历史记录中
	 */
	public void txbulsjl(){

		Db.use(Const.SCMDB).template("scmBuhuoZbbh.txbulsjl").update();

	}

	/**
	 * 总部查询补货明细历史记录
	 */
	public List<Record> selectBhmxls(Kv kv){

		kv.set("qx_pp", getPpqx(kv.getStr("userCode"))); //用户品牌权限


		List<Record> records = Db.use(Const.SCMDB).template("scmBuhuoZbbh.selectBhmxls",kv).find();

		return records;
	}

	/**
	 * 总部停补商品
	 */
	public RetKit zbtbsp(Kv kv){
		
		//查询停补商品表是否存在
		Integer cut = Db.use(Const.SCMDB).queryInt("select count(*) from scm_bhsp where mdid = ? and ysid = ? and spid = ? ",
                kv.get("mdid"), kv.get("ysid"), kv.get("spid"));
        int cnt = 0;
        if (cut > 0){
        	// 存在就更新
            cnt = Db.use(Const.SCMDB).update("update scm_bhsp set zt = 1 where mdid = ? and ysid = ? and spid = ? ",
                    kv.get("mdid"), kv.get("ysid"), kv.get("spid"));
        }else {
        	// 添加到停补商品中
            cnt  = Db.use(Const.SCMDB).update("insert into scm_bhsp(id, mdid, ysid, spid, ppid, zt) values(?,?,?,?,?,?)",
            				YitIdHelper.nextId(), kv.get("mdid"), kv.get("ysid"), kv.get("spid"), kv.get("ppid"), 1);
        }
        if(cnt>0) {
            return RetKit.ok("停补商品成功");
        }
        return RetKit.fail("停补商品失败");
	}
}
